package com.iretailer.report.analyze.device;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.iretailer.report.model.Device;
import com.iretailer.report.service.DevicesService;
import com.iretailer.report.util.TimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

/**
 * @Auther: xjw
 * @Date: 2019/9/25 0025 13:29
 * @Description:
 */
@Component
public class DeviceCommon {

    private static final Logger log = LoggerFactory.getLogger(DeviceCommon.class);
    @Autowired
    private DevicesService devicesService;


    /**
     * 更新设备的信息
     */
    public void updateDevice(Device device, LocalDateTime lastDataTime, String macAddr, String ipAddr, String serialNumber) {

//        Device device = devicesService.selectByDeviceId(deviceId);
        long m = Duration.between(LocalDateTime.now(), device.getUpdateTime()).toMinutes();
        if (m >= 5 || m < 0) {
            if (StringUtils.isNotEmpty(serialNumber)) {
                device.setSerialNumber(serialNumber);
            }
            if (StringUtils.isNotEmpty(macAddr)) {
                device.setMacAddress(macAddr);
            } else if (!StringUtils.isNotEmpty(device.getMacAddress())) {
                device.setMacAddress(" ");
            }
            if (StringUtils.isNotEmpty(ipAddr)) {
                device.setIpAddress(ipAddr);
            } else if (!StringUtils.isNotEmpty(device.getIpAddress())) {
                device.setIpAddress("");
            }
            device.setUpdateTime(LocalDateTime.now());
            if (lastDataTime != null) {
                device.setLastDataTime(lastDataTime);
            }
            devicesService.analysisUpdateDevice(device);
            log.debug("{} {} update {}", LocalDateTime.now(), device.getDeviceId());
        } else {
            log.debug("{} {} not update {}", LocalDateTime.now(), device.getDeviceId());
        }
    }

    public boolean judgeBusinessTime(ZonedDateTime time, ZoneId timeZone, String startTime, String endTime) {
        if (startTime != null && endTime != null) {
            ZonedDateTime start = ZonedDateTime.of(time.toLocalDate(), TimeUtil.parse_LocalTime(startTime), timeZone);
            ZonedDateTime end = ZonedDateTime.of(time.toLocalDate(), TimeUtil.parse_LocalTime(endTime), timeZone);
            //  time >=start  time<end
            if (!time.isBefore(start) && time.isBefore(end)) {
                return true;
            }
        }
        return false;
    }

}
